﻿function isNumber(n)
{
    return !isNaN(parseFloat(n)) && isFinite(n);
}

function round(num, digits)
{
    var multiplier = Math.pow(10, digits);
    return Math.round(num * multiplier) / multiplier;
}

function stringFormat(str, arr)
{
    if (!$.isArray(arr))
        arr = $.grep(arguments, function (item, index) { return index != 0; });

    return str.replace(/\{([0-9]+)\}/g, function (wholematch, firstmatch)
    {
        return arr[(+firstmatch)];
    });
}

Date.prototype.stringify = function ()
{
    return stringFormat("{0}/{1}/{2}", this.getFullYear(), this.getMonth() + 1, this.getDate());
}

Date.prototype.addDays = function (num)
{
    var newDate = new Date(this.getTime());
    newDate.setDate(newDate.getDate() + num);
    return newDate;
}

$.fn.show_loading = function (show, css)
{
    if (show)
    {
        this.css({"position": "relative", "z-index":"0"});
        var div = $("<div class='coverDiv'>");
        if (css)
            div.css(css);
        this.append(div);
        this.css({ "min-height": "50px" });
        div.append(stringFormat("<span class='tbl_loadingGif' style='margin:{0}px {1}px'></span>", Math.ceil(div.height() / 2) - 8, div.width() / 2 - 8));
    }
    else
    {
        this.css({ "min-height": "" });
        this.find('.coverDiv').remove();
    }
}

function log(str)
{
    if (window.console)
        console.log(str);
}

$.fn.waterMark = function (options)
{
    options = $.extend({
        text: "Search"
    }, options);

    var setMark = function (el)
    {
        var wm = $("<div class='WaterMark'>");
        $(wm).attr('wm_i', "_" + $(el).attr('wm_i'))
        wm.html(stringFormat("<div>{0}</div>", options.text));
        $(el).after(wm);
        wm.find("div").css({ "top": -$(el).height() - 8, "left": 10 });
        $(el).data("wm", wm);
    }

    $.each(this, function ()
    {
        var id = Math.random();
        $(this).attr('wm_i', id);
        if (!$(this).val())
            setMark(this);
        $(this).focus(function ()
        {
            var id = "_" + $(this).attr('wm_i');
            $(stringFormat("[wm_i={0}]", id)).remove();
        });
        $(this).blur(function ()
        {
            if (!$(this).val())
                setMark($(this));
        });
        $(this).keyup(function ()
        {
            if (!$(this).val())
            {
                setMark($(this));
            }
            else if ($(this).data("wm"))
            {
                var id = "_" + $(this).attr('wm_i');
                $(stringFormat("[wm_i={0}]", id)).remove();
            }
        });
    });

    return this;
}